package org.wx.zk.lock;

import lombok.extern.slf4j.Slf4j;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.ZooKeeper;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.wx.zk.comm.ZKUtils;

/**
 * @description: 分布式锁的测试
 * @author: wangxun
 * @createDate: 2021/3/24
 * @version: 1.0
 */
@Slf4j
public class TestLock {
    ZooKeeper zk;


    @Before
    public void getZK(){
        zk = ZKUtils.getZK();

    }


    /**
     * 分布式获取锁
     */
    @Test
    public void testLock(){
        for (int i = 0; i < 10; i++) {
            new Thread(()->{
                final LockWatch lockWatch = new LockWatch();
                lockWatch.setZk(zk);
                lockWatch.setThreadName(Thread.currentThread().getName());

                lockWatch.tryLock();

                // 执行业务代码
//                try {
//                    Thread.sleep(1000);
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
                try {
                    log.info("当前{} 持有锁",lockWatch.getRootData());
                } catch (KeeperException e) {
                    e.printStackTrace();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                lockWatch.unLock();

            }).start();
        }

        while (true){

        }
    }

    @After
    public void close(){
        ZKUtils.closeZK();
    }
}
